/**
 * 
 */
package grid;

import alg.Evaluation;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.jgap.Configuration;
import org.jgap.Genotype;
import org.jgap.IChromosome;
import util.GridConf;
import util.Utils;
import static grid.Constants.*;
import static alg.Constants.*;

/**
 * @author Darko
 *
 */
public class Breeder {

    private static String inputFile;
    private static String outputFile;
    private static String logFile;
    private static int seasons;
    private static int epoch;
    private static int island;
    private static int islands;
    private static int migrationWidth;

    private static void setup(String[] args) {
        if (args.length < 5) {
            throw new IllegalArgumentException();
        }
        seasons = Integer.parseInt(args[0]);
        if (seasons < 0) {
            throw new IllegalArgumentException();
        }
        epoch = Integer.parseInt(args[1]);
        island = Integer.parseInt(args[2]);
        islands = Integer.parseInt(args[3]);
        migrationWidth = Integer.parseInt(args[4]);
        inputFile = "population" + island + "_" + epoch + EXTENSION;
        outputFile = "population" + island + "_" + (epoch + 1) + EXTENSION;
        logFile = "breeder" + island + "_" + epoch + LOG_POSTFIX;
    }

    public static void main(String[] args) throws Exception {
        setup(args);

        Configuration conf = Utils.getDefaultConfiguration(
                20, new Evaluation(GridConf.getDwConfiguration()));

        List<Genotype> populations = new ArrayList<Genotype>();
        List<IChromosome> bestChromosomes = new ArrayList<IChromosome>();
        Genotype mainPopulation = null;
        for (int i = -migrationWidth; i <= migrationWidth; i++) {
            int index = island + i <= 0 ? islands + island + i : island + i;
            index = index > islands  ? index - islands : index;
            if (epoch > 0) {
                inputFile = "population" + index + "_" + epoch + EXTENSION;
                Genotype population = Utils.loadGenotypeFromGZIP(inputFile, conf);
                populations.add(population);
                bestChromosomes.add(population.getFittestChromosome());
                if (i == 0) {
                    mainPopulation = population;
                }
            }
        }

        // Give material to the previous and to the next breeders
        Random r = new Random(System.currentTimeMillis());
        if (populations.size() > 1) {
            for (int k = 0; k < populations.size(); k++) {
                int i = 0;
                do {
                    i = r.nextInt(populations.size() - 1);
                } while (mainPopulation.equals(populations.get(i)));
                mainPopulation.getPopulation().setChromosome(
                        i, bestChromosomes.get(k));
            }
        }


        String head = "breeder" + inputFile.substring(inputFile.length() - 6, inputFile.length() - 3);
        String start = java.text.DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(new Date());
        long startTime = System.currentTimeMillis();
        StringBuilder log = new StringBuilder();
        for (int i = 0; i < seasons; i++) {
            mainPopulation.evolve();
            log.append((i + 1) + ": " + MAX_VALUE + " " + mainPopulation.getFittestChromosome().getFitnessValue() + " " + (MAX_VALUE - mainPopulation.getFittestChromosome().getFitnessValue()) + "\n");
        }
        head += " " + mainPopulation.getFittestChromosome().getFitnessValue();
        long endTime = System.currentTimeMillis();
        log.append("\nTotal evolution time: " + (endTime - startTime) + " ms");
        String end = java.text.DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(new Date());
        String summary = head + " " + start + " " + end + " " + mainPopulation.getFittestChromosome().getFitnessValue();
        String finalLog = summary + "\n" + start + "\nEnd: " + end + "\n" + log.toString();

        Utils.saveGenotypeToGZIP(outputFile, mainPopulation);
        Utils.saveStringToGZIP(logFile, finalLog);
    }
}
